/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package player;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

public class WebServer {

    static RandomAccessFile raf;

    static String file = "C:/01.avi";
    static String nom = "file";
    static String client = "";
    static int port = 80;

    

    WebServer(String fichier) throws Exception
    {
        init(fichier);
    }
    
    WebServer(String fichier, int tcp_port) throws Exception
    {
        port = tcp_port;
        init(fichier);
    }
    
    private void init(String fichier) throws Exception
    {
        file = fichier.replace("\\", "/");
        nom = "/" + fichier;
        //nom ="/home/matthieu/01.avi";
        
        raf = new RandomAccessFile(new File(fichier), "r");
        
        Start();
    }
    
    
    public static void Start() throws Exception
    {

        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/media" + nom, new MyHandler());
        server.setExecutor(null); // creates a default executor
        
        // demarre le serveur dans un nouveau thread
        server.start(); 
    }

    static class MyHandler implements HttpHandler {

        public void handle(HttpExchange t) throws IOException {


            t.sendResponseHeaders(300, raf.length());
            OutputStream os = t.getResponseBody();
            
            //String old = client.substring(0, client.lastIndexOf(":"));
            client = t.getRemoteAddress().toString();
            //if ( old.equals(client.substring(0, client.lastIndexOf(":"))) )
                System.out.println("\nClient web : " + client);
            
            loadFile(os);
            os.close();
        }
    }
    
    //static private byte[] loadFile(String f) throws IOException {
    static private void loadFile(OutputStream o) throws IOException {



        byte[] buf = new byte[8];


        int n = 0;

        // Lecture du fichier
        while ((n = raf.read(buf)) >= 0) {
            for (int i = 0; i < 8; i++) //if ( i< buf.size()-1)
            {
                o.write(buf[i]);
            }
        }
        
        raf.seek(0);
        

    }
    
    @Override
    public void finalize() throws IOException
    {
        raf.close();
    }
    
    public static void configure(String fichier, int tcp_port)
    {
        file = fichier;
        port = tcp_port;
    }

    public String toString()
    {
        return "Server : http://127.0.0.1:" + port + "/media" + nom;
    }

}
